package com.paohe.lianxin_pda.utils.port;

import android.content.Context;
import android.content.Intent;
import com.paohe.lianxin_pda.MainActivity;
import com.paohe.lianxin_pda.utils.common.CacheActivity;
import com.paohe.lianxin_pda.utils.common.ConfigUtils;
import com.paohe.lianxin_pda.utils.toast.CustomToast;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 封装Retrofit接口
 */
public class PackageRetrofit {

    //发起请求
    public static VisitPort httpRequest() {
        //使用拦截器，添加请求头
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS);
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request origonal = chain.request();
                Request request = origonal.newBuilder()
                        .header("Content-type",ConfigUtils.CONTENT_TYPE)
                        .header("Authorization",ConfigUtils.TOKEN)
                        .header("Accept","*/*")
                        .method(origonal.method(),origonal.body())
                        .build();
                return chain.proceed(request);
            }

        });

        //发起网络请求
        OkHttpClient client = httpClient.build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ConfigUtils.URL)
                // 支持把请求的json转换bean
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
        VisitPort visitPort = retrofit.create(VisitPort.class);
        //进行参数传递
        return visitPort;
    }

    //登录过期的处理方法
    public static Intent pdaPastDue(Context context, Integer code) {
        Intent toLogin = null;
        if (code == ConfigUtils.TOKEN_PASS) {
            ConfigUtils.TOKEN = "";
            CustomToast.showToast(context, "登录过期，请重新登录！");
            CacheActivity.finishActivity();//关闭所有activity
            toLogin = new Intent(context, MainActivity.class);
        }
        return toLogin;
    }

}
